package org.geektimes.configuration.microprofile.source.servlet;

import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.spi.ConfigBuilder;
import org.eclipse.microprofile.config.spi.ConfigProviderResolver;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.logging.Logger;

/**
 * @Author: jipeng
 * @Description:
 * @see ServletConfigInitializer
 * @Date: Created in 2021/3/21 19:38
 */
public class ServletContextConfigInitializer implements ServletContextListener {
    private final Logger logger = Logger.getLogger(getClass().getName());

    private ServletContext servletContext;

    public ServletContextConfigInitializer(ServletContext servletContext){
        this.servletContext = servletContext;
    }

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        logger.info("===================== start ServletContextConfigInitializer contextInitialized method =====================");
        ServletContextConfigSource servletContextConfigSource = new ServletContextConfigSource(servletContext);
        //获取当前的ClassLoader
        ClassLoader classLoader = servletContext.getClassLoader();

        ConfigProviderResolver configProviderResolver = ConfigProviderResolver.instance();
        ConfigBuilder configBuilder = configProviderResolver.getBuilder();
        configBuilder.forClassLoader(classLoader);
        //默认配置源（内建的，固定的，静态的）
        configBuilder.addDefaultSources();
        //通过发现配置源 （动态的）
        configBuilder.addDiscoveredConverters();
        //增加扩展配置源 （扩展的，基于Servlet 引擎）
        configBuilder.withSources(servletContextConfigSource);
        // 添加转转器
        configBuilder.addDiscoveredConverters();
        //获取 Config
        Config config = configBuilder.build();
        //注册 Config 关联到当前 ClassLoader
        configProviderResolver.registerConfig(config,classLoader);
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
//        System.out.println("ServletContextConfigInitializer Destroyed");
    }
}
